/**
 * @author weileiming
 * @description 聊天功能组件
 */

import React, { useEffect } from "react";
import { ScrollView, View, Text } from "@tarojs/components";
import Taro from "@tarojs/taro";
import "./index.scss";

interface MessageType {
  id: number;
  content: string;
  isMe: boolean;
  initial: string;
}

interface ChatWindowProps {
  messages: MessageType[];
}

const ChatWindow = ({ messages }: ChatWindowProps) => {
  const scrollViewRef = React.useRef<any>();

  useEffect(() => {
    // 使用 nextTick 确保消息渲染完成
    Taro.nextTick(() => {
      if (scrollViewRef.current) {
        // 获取 ScrollView 的滚动高度
        const query = Taro.createSelectorQuery();
        query.select('.chat-content').boundingClientRect().exec(res => {
          const [rect] = res;
          if (rect) {
            // 接收最新消息 滚动到底部
            scrollViewRef.current.scrollTop = rect.height;
          }
        });
      }
    });
  }, [messages]);

  return (
    <ScrollView
      className="chat-window"
      scrollY
      scrollWithAnimation
      ref={scrollViewRef}
      scrollIntoView={`msg-${messages[messages.length - 1]?.id}`}
    >
      <View className="chat-content">
        {messages.map((message) => (
          <View
            key={message.id}
            id={`msg-${message.id}`}
            className={`message-wrapper ${
              message.isMe ? "message-right" : "message-left"
            }`}
          >
            <View
              className={`avatar ${
                message.isMe ? "avatar-right" : "avatar-left"
              }`}
            >
              <Text>{message.initial}</Text>
            </View>
            <View
              className={`message-bubble ${
                message.isMe ? "bubble-right" : "bubble-left"
              }`}
            >
              <Text className="message-text">{message.content}</Text>
            </View>
          </View>
        ))}
      </View>
    </ScrollView>
  );
};

export { MessageType };
export default ChatWindow;
